package com.example.data.jdbc.dao;

import com.example.data.jdbc.entity.User;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.PathBuilder;
import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

/**
 * <pre>
 * 第 1 种自定义 findByJpql
 * 第 2 种自定义 findCustomerBySpec
 * 第 3 种自定义 @see UserExtOperation # findExtends
 * </pre>
 *
 * @author fanhang
 */
public interface UserRepository extends UserExtOperation, CrudRepository<User, Long>, QuerydslPredicateExecutor<User> {
    PathBuilder<User> TABLE = new PathBuilder<>(User.class, "t_user");

    /**
     * 第 1 种自定义
     */
    @Query("select * from t_user where age > :age and remark like '%:remark%' ")
    List<User> findByJpql(int age, String remark);

    /**
     * 第 2 种自定义
     */
    default Iterable<User> findCustomerBySpec(int age, String remark) {
        PredicateBuilder<User> builder = new PredicateBuilder<>(User.class, "t_user");
        builder.add(":", "age", age);
        builder.add("like", "remark", remark);
        builder.get();
        return findAll(builder.get());
    }

    default Iterable<User> findCustomerBySpec2(int age, String remark) {
        BooleanExpression ageExp = TABLE.get("age", Integer.class).eq(age);
        BooleanExpression remarkExp = TABLE.getString("remark").like(remark);
        return findAll(ageExp.and(remarkExp));
    }

}
